package com.wn.util;

import com.wn.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

public class JWTUtil {
    /**
     * 生成公钥和私钥
     * @param publicFilename
     * @param privateFilename
     * @param secret
     */
    public static void generateKey(String publicFilename,String privateFilename,String secret){
        try {
            RsaUtils.generateKey(publicFilename,privateFilename,secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成令牌的方法
     * @param user
     * @param privateKey
     * @param time
     * @return
     */
    public static String generateToken(User user, String privateKey, Integer time){
        String token ="";
        try {
            token = Jwts.builder().claim("id", user.getId())
                    .claim("username", user.getName())
                    .setExpiration(DateTime.now().plusMinutes(time).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey)).compact();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 解析令牌
     * @param token
     * @param publicKey
     * @return
     */
    public static  User parserToken(String token,String publicKey){
        Claims body= null;
        User user=null;
        try {
             body = Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey)).parseClaimsJws(token).getBody();
            Integer id = body.get("id", Integer.class);
            String username = body.get("username", String.class);
            user = new User(id,username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
}
